package com.dyp.content_negotiation.configuration;

import com.dyp.content_negotiation.model.User;
import com.opencsv.CSVWriter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

public class CustomCsvConverter extends AbstractHttpMessageConverter<List<User>> {
    public CustomCsvConverter() {
        super(new MediaType("text", "csv")); // 声明支持的媒体类型
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return List.class.isAssignableFrom(clazz);
    }

    @Override
    protected List<User> readInternal(Class<? extends List<User>> clazz, HttpInputMessage inputMessage) {
        throw new UnsupportedOperationException("暂不支持读取CSV");
    }

    @Override
    protected void writeInternal(List<User> users, HttpOutputMessage outputMessage) throws IOException {
        try (Writer writer = new OutputStreamWriter(outputMessage.getBody()))  {
            CSVWriter csvWriter = new CSVWriter(writer);
            csvWriter.writeNext(new  String[]{"Name", "Address"});
            users.forEach(user  -> csvWriter.writeNext(new  String[]{user.getName(),  String.valueOf(user.getAddress())}));
        }
    }
}